<?php

require_once("configure.php");

$user = $_GET["user"];

function OutputCategory()
{
	global $MySqlLinkId, $user;
	$CategoryArray = Array();
	$result = mysql_query("SELECT Id, Name FROM BillCategory WHERE AccountName='".mysql_real_escape_string($user)."'", $MySqlLinkId);
	while(($row = mysql_fetch_row($result)))
	{
		$CategoryArray[] = Array((int)$row[0], $row[1]);
	}
	mysql_free_result($result);
	echo("var category_data = ".json_encode($CategoryArray).";");
}

function GetBillData()
{
	global $MySqlLinkId, $user;
	$BillData = Array();
	$sql = "SELECT Bill.Id, PayAmount, Name, Remark, CreateTime FROM Bill INNER JOIN BillCategory ON Bill.CategoryId = BillCategory.Id WHERE Bill.AccountName='".mysql_real_escape_string($user)."' AND CreateTime>='".date('Y-m-01', (time() - (12 * 30 * 24 * 60 * 60)))."' ORDER BY CreateTime ASC";
	$result = mysql_query($sql, $MySqlLinkId);
	while(($row = mysql_fetch_row($result)))
	{
		$BillData[] = Array($row[0], ((float)$row[1]) / 100, $row[2], $row[3], $row[4]);
	}
	mysql_free_result($result);
	return $BillData;
}

$MySqlLinkId = mysql_connect(DBHost, DBUser, DBPwd);
if($MySqlLinkId == FALSE)
{
	echo("alert('链接数据库失败！');var category_data=[];var bill_data=[];var chart1_xml='';var chart2_xml='';");
	exit();
}

if(FALSE == mysql_select_db(DB, $MySqlLinkId))
{
	echo("alert('".json_encode(mysql_error($MySqlLinkId))."');var category_data=[];var bill_data=[];var chart1_xml='';var chart2_xml='';");
	mysql_close($MySqlLinkId);
	exit();
}

$bill_data = GetBillData();
OutputCategory();
mysql_close($MySqlLinkId);

$BillCategory = Array();
$BillMonth = Array();
$CurrentMonthBillData = Array();
$now = strptime(date("Y-m-d"), "%Y-%m-%d");
foreach($bill_data as $d)
{
	$datetime = strptime($d[4], "%Y-%m-%d");
	if($now["tm_mon"] == $datetime["tm_mon"])
	{
		$BillCategory[$d[2]] += $d[1];
		$CurrentMonthBillData[] = $d;
	}

	$BillMonth[sprintf("%04d-%02d", ($datetime["tm_year"]+1900), ($datetime["tm_mon"]+1))] += $d[1];
}

echo("var bill_data = ".json_encode($CurrentMonthBillData).";");

$chart1_data = Array();
foreach($BillMonth as $k => $bm)
{
	$chart1_data[] = Array($k, $bm);
}
echo("var chart1_data = ".json_encode($chart1_data).";");

$chart2_data = Array();
foreach($BillCategory as $k => $bc)
{
	$chart2_data[] = Array($k, $bc);
}
echo("var chart2_data = ".json_encode($chart2_data).";");

?>